package me.zhujin.java.learnjava.myserver;

import me.zhujin.java.learnjava.myserver.util.CloseUtil;

import javax.script.ScriptException;
import java.io.IOException;
import java.net.Socket;

/**
 * 分发器
 * Created by zhujin on 10/20/16.
 * blog:www.zhujin.me
 * email: zhujin.nova@gmail.com
 */
public class MyDispatcher implements Runnable {

    private Socket client;
    private MyRequest request;
    private MyResponse response;
    private int code = 200;

    public MyDispatcher(Socket client) {
        this.client = client;
        try {
            response = new MyResponse(client);
            request = new MyRequest(client);
        } catch (IOException e) {
//            e.printStackTrace();
            code = 500;
            return;
        }


    }

    @Override
    public void run() {
        MyServlet servlet = null;
        try {
            servlet = new WebApp().getServlet(request.getUrl());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            this.code = 500;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            this.code = 500;
        } catch (InstantiationException e) {
            e.printStackTrace();
            this.code = 500;
        }


        try {
            if (null == servlet) {
                this.code = 404;
            } else {
                servlet.service(request, response);
            }
            response.pushToClilent(code);
        } catch (Exception e) {
            e.printStackTrace();
            this.code = 500;
        }

        CloseUtil.closeSocket(client);
    }


}
